<?php

/**
 * comment actions.
 *
 * @package    Nika
 * @subpackage comment
 * @author     Alexey Shapran (alexey.shapran@gmail.com)
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class commentActions extends sfActions
{
	/**
	 * Executes index action
	 *
	 * @param sfRequest $request A request object
	 */
	public function executeIndex(sfWebRequest $request)
	{
	}

	public function executeSubmit(sfWebRequest $request)
	{
		$this->forward404Unless($request->isMethod('post'));

		$this->form = new CommentForm();

		include_once $_SERVER['DOCUMENT_ROOT'] . '/securimage/securimage.php';
		$securimage = new Securimage();

		/*$captcha = array(
		 'recaptcha_challenge_field' => $request->getParameter('recaptcha_challenge_field'),
		 'recaptcha_response_field'  => $request->getParameter('recaptcha_response_field'),
		 );*/

		$com_body = trim(strip_tags($request->getParameter('body')));
		$ent_id = $request->getParameter('entity_id2');
		$ent_type = $request->getParameter('entity_type2');
		$us_id = $this->getUser()->getGuardUser()->getId();

		$this->form->bind(array(
	'body' => $com_body,
    'entity_id'   => $ent_id,
	'capcha_res'  => $securimage->check($_POST['captcha_code']) ? 'yes' : 'no',
    'entity_type' => $ent_type,
  	'user_id'     => $us_id,
	'_csrf_token' => $request->getParameter('_csrf_token'),
		));

		if($this->form->isValid())
		{
			$this->form->save();
			// Copying to base
			// Проверяем, есть ли на форуме такая новость?
			// тип записи (где искать)
			switch($ent_type)
			{
				case 'article' : $pcode = '33333'; $actual = Doctrine::getTable('Article')->findOneBy('id', $ent_id); $routename = 'article_view'; $categ = Doctrine::getTable('ArticleCategory')->findOneBy('id',$actual['category_id']); break;
				case 'reliz' : $pcode = '44444'; $actual = Doctrine::getTable('Reliz')->findOneBy('id', $ent_id); $routename = 'reliz_view'; $categ = Doctrine::getTable('RelizCategory')->findOneBy('id',$actual['category_id']); break;
				case 'news' : $pcode = '22222'; $actual = Doctrine::getTable('News')->findOneBy('id', $ent_id); $routename = 'news_view'; break;
				case 'post' : $pcode = '55555'; $actual = Doctrine::getTable('BlogPost')->findOneBy('id', $ent_id); $routename = 'blogs_view'; break;
				default : $pcode = NULL; break;
			}

			// LOOKING FOR $PCODE

			if($pcode)
			{
				$con = Doctrine_Manager::getInstance()->connection();
				$query = "SELECT * FROM for_topics WHERE forum_id = $pcode AND subject LIKE '".$actual['title']."'";
				$st = $con->execute($query);
				$all = $st->fetchAll();

				// IF COUNT
					
				if( count($all) == 0 )
				{
					$query = "INSERT INTO for_topics(poster, subject, forum_id) VALUES ('".$this->getUser()->getGuardUser()->getUsername()."','".$actual['title']."', ".$pcode.")";
					$st = $con->execute($query);

					$query = 'UPDATE for_forums SET num_topics = num_topics+1 WHERE id = '.$pcode;
					$con->execute($query);

					$needlink = 1;
					$link = '';
				}

				// END IF

				$query = "SELECT * FROM for_topics WHERE forum_id = $pcode AND subject LIKE '".$actual['title']."'";
				$st = $con->execute($query);
				$all = $st->fetchAll();

				// IF COUNT == 1
				if (count($all) == 1)
				{
					$link = '';
					$a = '[url=';
					if(isset($needlink))
					{
						switch($ent_type)
						{
							case 'article' : $link = $this->generateUrl($routename, array('categoryalias'=>$categ['alias'], 'alias'=>$actual['alias'] ), true ); break;
							case 'reliz' : $link = $this->generateUrl ($routename, array('categoryalias'=>$categ['alias'], 'alias'=>$actual['alias'] ), true) ; break;
							case 'news' : $link = $this->generateUrl($routename, array('alias'=>$actual['alias'] ), true); break;
							case 'post' : $link = $this->generateUrl($routename, array('id'=>$actual['id'] ), true); break;
						}
						$link = ' '.$a.$link.']Подробнее[/url]';
					}

					$query = "SELECT * FROM for_users WHERE email LIKE '".$this->getUser()->getGuardUser()->getUsername()."'";
					$st = $con->execute($query);
					$user = $st->fetchAll();

					$query = "INSERT INTO for_posts(poster, poster_id, message, topic_id, posted)
					VALUES ( '".$user[0]['username']."','".$user[0]['id']."', '$com_body $link', '".$all[0]['id']."', '".time()."' )";
					$st = $con->execute($query);

					$query = "SELECT * FROM for_posts WHERE topic_id = ".$all[0]['id']." ORDER BY posted DESC";
					$st = $con->execute($query);

					$this_mes = $st->fetchAll();

					$query = 'UPDATE for_topics SET last_poster = "'.$this_mes[0]['poster'].'", num_replies = '.count($this_mes).', last_post = '.time().', last_post_id = '.$this_mes[0]['id'].' WHERE id = '.$all[0]['id'];
					$con->execute($query);

					if(isset($needlink))
					{
						$query = 'UPDATE for_topics SET first_post_id = "'.$this_mes[0]['id'].'" WHERE id = '.$all[0]['id'];
						$con->execute($query);
					}

					/*
					 $query = "SELECT * FROM for_posts WHERE topic_id = ".$all[0]['id']." ORDER BY posted DESC";
					 $st = $con->execute($query);

					 $this_mes = $st->fetchAll();

					 $query = 'UPDATE for_topics SET num_replies = '.count($this_mes).', last_post = '.time().', last_post_id = '.$this_mes[0]['id'].' WHERE id = '.$all[0]['id'] ;
					 $con->execute($query);
					 */
				}

				$query = 'SELECT count(*) FROM for_topics WHERE forum_id = '.$pcode;
				$st = $con->execute($query);
				$all = $st->fetch();

				$query = 'SELECT SUM(num_replies) FROM for_topics WHERE forum_id = '.$pcode;
				$st = $con->execute($query);

				$c = $st->fetch();

				$query = 'UPDATE for_forums SET last_poster = "'.$this_mes[0]['poster'].'", num_topics = '.$all[0].', num_posts = '.$c[0].', last_post = '.time().' WHERE id = '.$pcode;
				$con->execute($query);
			}
		}
		else
		{
			$this->getUser()->setAttribute('form', $this->form);
		}
		$prevpage = $_SERVER['HTTP_REFERER'];
		$this->redirect($prevpage);
	}

	public function executeSubmitnext(sfWebRequest $request)
	{
		$this->forward404Unless($request->isMethod('post'));
		$this->urgform = new UnregCommentForm();

		/*$captcha = array(
		 'recaptcha_challenge_field' => $request->getParameter('recaptcha_challenge_field'),
		 'recaptcha_response_field'  => $request->getParameter('recaptcha_response_field'),
		 );*/

		include_once $_SERVER['DOCUMENT_ROOT'] . '/securimage/securimage.php';
		$securimage = new Securimage();

		$com_body = trim(strip_tags($request->getParameter('body')));
		$ent_id = $request->getParameter('entity_id2');
		$ent_type = $request->getParameter('entity_type2');
		$us_name = $request->getParameter('guest_name');

		$this->urgform->bind(array(
	'body' => $com_body,
    'entity_id'   => $ent_id,
		//'captcha'	  => $captcha,
	'capcha_res'  => $securimage->check($_POST['captcha_code']) ? 'yes' : 'no',
    'entity_type' => $ent_type,
	'guest_name'  => $us_name,
	'_csrf_token' => $request->getParameter('_csrf_token'),
		));

		if($this->urgform->isValid())
		{
			$this->urgform->save();

			switch($ent_type)
			{
				case 'article' : $pcode = '33333'; $actual = Doctrine::getTable('Article')->findOneBy('id', $ent_id); $routename = $ent_type.'_view'; $categ = Doctrine::getTable('ArticleCategory')->findOneBy('id',$actual['category_id']); break;
				case 'reliz' : $pcode = '44444'; $actual = Doctrine::getTable('Reliz')->findOneBy('id', $ent_id); $routename = $ent_type.'_view'; $categ = Doctrine::getTable('RelizCategory')->findOneBy('id',$actual['category_id']); break;
				case 'news' : $pcode = '22222'; $actual = Doctrine::getTable('News')->findOneBy('id', $ent_id); $routename = $ent_type.'_view'; break;
				case 'post' : $pcode = '55555'; $actual = Doctrine::getTable('BlogPost')->findOneBy('id', $ent_id); $routename = 'blogs_view'; break;
				default : $pcode = NULL; break;
			}

			// LOOKING FOR PCODE

			if($pcode)
			{
				$con = Doctrine_Manager::getInstance()->connection();
				$query = "SELECT * FROM for_topics WHERE forum_id = $pcode AND subject LIKE '".$actual['title']."'";
				$st = $con->execute($query);
				$all = $st->fetchAll();

				// IF COUNT

				if( count($all) == 0 )
				{
					$query = "INSERT INTO for_topics(poster, subject, forum_id) VALUES ('".$us_name."','".$actual['title']."', ".$pcode.")";
					$st = $con->execute($query);

					$query = 'UPDATE for_forums SET num_topics = num_topics+1 WHERE id = '.$pcode;
					$st->execute($query);

					$needlink = 1;
					$link = '';
				}

				// END IF
					
				$query = "SELECT * FROM for_topics WHERE forum_id = $pcode AND subject LIKE '".$actual['title']."'";

				$st = $con->execute($query);
				$all = $st->fetchAll();

				// IF COUNT == 1
				if (count($all) == 1)
				{
					$link = '';
					$a = '[url=';
					if(isset($needlink))
					{
						switch($ent_type)
						{
							case 'article' : $link = $this->generateUrl($routename, array('categoryalias'=>$categ['alias'], 'alias'=>$actual['alias'] ), true ); break;
							case 'reliz' : $link = $this->generateUrl ($routename, array('categoryalias'=>$categ['alias'], 'alias'=>$actual['alias'] ), true) ; break;
							case 'news' : $link = $this->generateUrl($routename, array('alias'=>$actual['alias'] ), true); break;
							case 'post' : $link = $this->generateUrl($routename, array('id'=>$actual['id'] ), true); break;
						}
						$link = ' '.$a.$link.']Подробнее[/url]';
					}

					$query = "INSERT INTO for_posts(poster, poster_id, message, topic_id, posted)
					VALUES ( '".$us_name."', 1 , '$com_body $link', '".$all[0]['id']."', '".time()."' )";
					$st = $con->execute($query);

					$query = "SELECT * FROM for_posts WHERE topic_id = ".$all[0]['id']." ORDER BY posted DESC";
					$st = $con->execute($query);

					$this_mes = $st->fetchAll();

					$query = 'UPDATE for_topics SET last_poster = "'.$this_mes[0]['poster'].'", num_replies = '.count($this_mes).', last_post = '.time().', last_post_id = '.$this_mes[0]['id'].' WHERE id = '.$all[0]['id'];
					$con->execute($query);
						
					if(isset($needlink))
					{
						$query = 'UPDATE for_topics SET first_post_id = "'.$this_mes[0]['id'].'" WHERE id = '.$all[0]['id'];
						$con->execute($query);
					}
				}

				$query = 'SELECT count(*) FROM for_topics WHERE forum_id = '.$pcode;
				$st = $con->execute($query);
				$all = $st->fetch();

				$query = 'SELECT SUM(num_replies) FROM for_topics WHERE forum_id = '.$pcode;
				$st = $con->execute($query);

				$c = $st->fetch();

				$query = 'UPDATE for_forums SET last_poster = "'.$this_mes[0]['poster'].'", num_topics = '.$all[0].', num_posts = '.$c[0].', last_post = '.time().' WHERE id = '.$pcode;
				$con->execute($query);
			}
			$prevpage = $_SERVER['HTTP_REFERER'];
			$this->redirect($prevpage);
		}
		else
		{
			$this->getUser()->setAttribute('urgform', $this->urgform);
			$prevpage = $_SERVER['HTTP_REFERER'];
			$this->redirect($prevpage);
		}
	}

	public function executeDelete(sfWebRequest $request)
	{
		$comid = $request->getParameter('comid');
		$uid = $this->getUser()->getGuardUser()->getId();
		Comment::deletecommentbyidanduserid($comid, $uid);
			
		return sfView::NONE;
	}
	public function executeDeletefromindex(sfWebRequest $request)
	{
		$pictid = $request->getParameter('photoid');
		$picture = Media::retrieveUserIdByMediaFileId($pictid);

		$this->forward404Unless( $this->getUser()->getGuardUser()->getId() == $picture['user_id'] );

		$comid = $request->getParameter('comid');
		Comment::deletecommentbyid($comid);
		$fromwhere = $_SERVER['HTTP_REFERER'];
		$this->redirect($fromwhere);

	}
}
